<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <region :options="regionSearchOptions"></region>

      <el-date-picker
        v-model="listQuery.startTime"
        type="date"
        class="filter-item"
        :editable="false"
        :clearable="false"
        :placeholder="$t('Start_time')"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
      ></el-date-picker>

      <el-date-picker
        v-model="listQuery.endTime"
        type="date"
        class="filter-item"
        :editable="false"
        :clearable="false"
        :placeholder="$t('End_time')"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
      ></el-date-picker>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
        >{{ $t("Search") }}
      </el-button>
    </div>

    <el-card class="box-card">
      <h4>{{ $t("Summary") }}</h4>
      <div class="table-layout">
        <el-row>
          <el-col :span="3" class="table-cell-title">{{
            $t("订单总数")
          }}</el-col>
          <el-col :span="3" class="table-cell-title">{{
            $t("交易总额")
          }}</el-col>
          <el-col :span="3" class="table-cell-title">{{
            $t("退款总额")
          }}</el-col>
          <el-col :span="3" class="table-cell-title">{{
            $t("销售总额")
          }}</el-col>
          <el-col :span="3" class="table-cell-title">{{
            $t("税费总交易总额")
          }}</el-col>
          <el-col :span="3" class="table-cell-title">{{
            $t("税费总交易明细")
          }}</el-col>
          <el-col :span="3" class="table-cell-title">{{
            $t("税费总退款总额")
          }}</el-col>
          <el-col :span="3" class="table-cell-title">{{
            $t("税费总退款明细")
          }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="3" class="table-cell">{{
            totalStatistics.totalCount
          }}</el-col>
          <el-col :span="3" class="table-cell"
            >${{
              (totalStatistics.totalAmount + totalStatistics.refundTotalAmount)
                | floorTwoDecimal
            }}</el-col
          >
          <el-col :span="3" class="table-cell"
            >${{ totalStatistics.refundTotalAmount | floorTwoDecimal }}</el-col
          >
          <el-col :span="3" class="table-cell"
            >${{
              (totalStatistics.totalAmount +
                totalStatistics.refundTotalAmount -
                totalStatistics.refundTotalAmount)
                | floorTwoDecimal
            }}</el-col
          >
          <el-col :span="3" class="table-cell"
            >${{ totalStatistics.taxTotalAmount | floorTwoDecimal }}</el-col
          >
          <el-col :span="3" class="table-cell">
            <div v-for="tax in totalStatistics.taxDetailLs" :key="tax.code">
              {{ tax.code }}：${{ tax.totalAmount | floorTwoDecimal }}
            </div>
          </el-col>
          <el-col :span="3" class="table-cell"
            >${{
              totalStatistics.taxRefundTotalAmount | floorTwoDecimal
            }}</el-col
          >
          <el-col :span="3" class="table-cell">
            <div
              v-for="tax in totalStatistics.taxRefundDetailLs"
              :key="tax.code"
            >
              {{ tax.code }}：${{ tax.totalAmount | floorTwoDecimal }}
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <el-card class="box-card">
      <h4>{{ $t("Details") }}</h4>
      <!-- 查询结果 -->
      <el-table
        v-loading="listLoading"
        :data="list"
        :element-loading-text="$t('Searching')"
        border
        fit
        highlight-current-row
      >
        <el-table-column
          type="index"
          :index="getIndex"
          width="50"
        ></el-table-column>

        <el-table-column align="center" :label="$t('店铺')" prop="shopName" />

        <!-- <el-table-column align="center" :label="$t('Start_time')" prop="totalCount">
          <template slot-scope="scope">
            {{listQuery.startTime}}
          </template>
        </el-table-column> -->

        <!-- <el-table-column align="center" :label="$t('End_time')" prop="totalCount">
          <template slot-scope="scope">
            {{listQuery.endTime}}
          </template>
        </el-table-column> -->

        <el-table-column
          align="center"
          :label="$t('订单总数')"
          prop="totalCount"
        />

        <el-table-column
          align="center"
          :label="$t('订单总额')"
          prop="totalAmount"
        >
          <template slot-scope="scope">
            {{ scope.row.totalAmount | floorTwoDecimal }}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          :label="$t('税费总额')"
          prop="taxTotalAmount"
        >
          <template slot-scope="scope">
            {{ scope.row.taxTotalAmount | floorTwoDecimal }}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          property="taxDetailLs"
          :label="$t('税费详情')"
        >
          <template slot-scope="scope">
            <div v-for="tax in scope.row.taxDetailLs" :key="tax.code">
              {{ tax.code }}: {{ tax.totalAmount | floorTwoDecimal }}
            </div>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          :label="$t('Operate')"
          width="300"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              v-permission="['GET /admin/order/order_day_statistics']"
              type="primary"
              size="mini"
              @click="handleDetail(scope.row)"
              >{{ $t("Details") }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
    </el-card>
    <div style="margin: 10px 0">
      <el-select
        v-model="orderTypeQuery.payType"
        :placeholder="$t('请选择') + $t('Pay_Type')"
        @change="payTypeChange"
        clearable
      >
        <el-option
          v-for="item in payTypeList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-select
        v-model="orderTypeQuery.shopId"
        clearable
        :placeholder="$t('Please_select_store_')"
      >
        <el-option
          v-for="item in shops"
          :value="item.id"
          :label="item.name"
        ></el-option>
      </el-select>
      <el-select
        v-model="orderTypeQuery.orderSource"
        :placeholder="$t('请选择') + $t('Source_of_order')"
        @change="orderTypeChange"
        clearable
      >
        <el-option
          v-for="item in orderSourceList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button type="primary" icon="el-icon-search" @click="getOrderTypeList"
        >{{ $t("Search") }}
      </el-button>
    </div>
    <el-card class="box-card">
      <h4>{{ $t("Details") }}</h4>
      <el-table
        v-loading="orderTypeLoading"
        :data="orderTypeList"
        :element-loading-text="$t('Searching')"
        border
        fit
        highlight-current-row
      >
        <el-table-column
          type="index"
          :index="getIndex"
          width="50"
        ></el-table-column>
        <el-table-column
          align="center"
          :label="$t('订单编号')"
          prop="orderSn"
        />
        <el-table-column
          align="center"
          :label="$t('门店名称')"
          prop="shopName"
        />
        <el-table-column
          align="center"
          :label="$t('用户账号')"
          prop="username"
        />
        <el-table-column
          align="center"
          :label="$t('订单状态')"
          prop="orderStatus"
        >
          <template slot-scope="scope">
            <el-tag>{{ orderStatus(scope.row.orderStatus) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          :label="$t('订单来源')"
          prop="orderSource"
        >
          <template slot-scope="scope">
            <el-tag>{{ orderSource(scope.row.orderSource) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          :label="$t('订单类型')"
          prop="orderType"
        >
          <template slot-scope="scope">
            <el-tag>{{
              scope.row.orderType ? orderType(scope.row.orderType) : "---"
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          :label="$t('商品总费用')"
          prop="goodsPrice"
        >
          <template slot-scope="scope">
            <el-tag>$ {{ scope.row.goodsPrice }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          width="200"
          :label="$t('付款时间')"
          prop="payTime"
        >
          <template slot-scope="scope">
            {{ scope.row.payTime ? scope.row.payTime : "--- ---" }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          width="200"
          :label="$t('添加时间')"
          prop="addTime"
        >
          <template slot-scope="scope">
            <el-tag effect="dark" type="success">
              <i class="el-icon-time"></i> {{ scope.row.addTime }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          :label="$t('Operate')"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              icon="el-icon-tickets"
              v-permission="['GET /admin/order/order_day_statistics']"
              type="primary"
              @click="handleOrderDetail(scope.row)"
              size="mini"
              >{{ $t("Details") }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="orderTotal > 0"
        :total="orderTotal"
        :page.sync="orderTypeQuery.page"
        :limit.sync="orderTypeQuery.limit"
        @pagination="getOrderTypeList"
      />
    </el-card>
  </div>
</template>

<script>
import { allForPerm } from "@/api/shop";
import {
  orderTotalStatistics,
  orderMonthStatistics,
  orderTypeStatistics,
} from "@/api/order";
import Region from "@/components/Region";
import BackToTop from "@/components/BackToTop";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
import store from "@/store";

export default {
  name: "orderSummaryStatistic",
  components: {
    Region,
    BackToTop,
    Pagination,
  },
  data() {
    const orderTypeObj = {
      1: this.$t("自提"),
      2: this.$t("配送"),
      3: this.$t("堂食"),
      4: this.$t("外带"),
    };
    const orderSourceObj = {
      1: this.$t("Phone_App"),
      2: this.$t("Store_Order"),
      3: this.$t("Online_Mall"),
      4: this.$t("Subscription"),
    };
    const orderStatusObj = {
      // (101：下单 102：取消 103：自动取消 201：已支付 202：退款 203：退款成功 301：待收货 401：确认收货 402：自动确认收货)
      101: this.$t("下单"),
      102: this.$t("取消"),
      103: this.$t("自动取消"),
      201: this.$t("已支付"),
      202: this.$t("退款"),
      203: this.$t("退款成功"),
      301: this.$t("待收货"),
      401: this.$t("确认收货"),
      402: this.$t("自动确认收货"),
    };
    return {
      orderTypeObj,
      orderSourceObj,
      orderStatusObj,
      // 当前店铺
      shop: store.state.user.shop,
      listLoading: true,
      orderTypeLoading: true,
      total: 0,
      orderTotal: 0,
      listQuery: {
        page: 1,
        limit: 20,
        // 开始时间
        startTime: undefined,
        // 结束时间
        endTime: undefined,
      },
      orderTypeQuery: {
        shopId: undefined,
        payType: undefined,
        orderSource: undefined,
        page: 1,
        limit: 10,
      },
      regionSearchOptions: {},
      totalStatistics: {},
      list: [],
      shops: [],
      orderTypeList: [],
    };
  },
  created() {
    this.listQuery.startTime = this.getFirstDayOfMonth(this.getVancouverDate()); //当月第一天
    this.listQuery.endTime = this.getVancouverDate();

    this.getList();
    this.getOrderTypeList();
    allForPerm().then((response) => {
      this.shops = response.data.data.list;
    });
  },
  methods: {
    handleOrderDetail(row) {
      this.$router.push({ path: "/order/detail", query: { id: row.id } });
    },
    test(row) {
    },
    search() {},
    payTypeChange(val) {},
    orderTypeChange(val) {},
    orderType(val) {
      // 订单类型 1 自提  2 配送 3 堂食 4 外带
      return this.orderTypeObj[val];
    },
    orderSource(val) {
      // 订单来源 1:手机app下单,2:门店下单,3:官网商城,4:订阅
      return this.orderSourceObj[val];
    },
    orderStatus(val) {
      // (101：下单 102：取消 103：自动取消 201：待发货 202：退款 203：退款成功 301：待收货 401：确认收货 402：自动确认收货)
      return this.orderStatusObj[val];
    },
    getOrderTypeList() {
      orderTypeStatistics(this.orderTypeQuery)
        .then((res) => {
          const records = res.data.data;
          this.orderTypeList = records.list;
          this.orderTotal = records.total;
          this.orderTypeLoading = false;
        })
        .catch((e) => {
          this.orderTypeList = [];
          this.orderTotal = 0;
          this.orderTypeLoading = false;
        });
    },
    getList() {
      // 汇总查询
      orderTotalStatistics(this.listQuery)
        .then((response) => {
          this.totalStatistics = response.data.data;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });

      // 详情查询
      orderMonthStatistics(this.listQuery)
        .then((response) => {
          this.list = response.data.data.list;
          this.total = response.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
    handleFilter() {
      this.getList();
    },
    handleDetail(row) {
      let query = {
        shopId: row.shopId,
        shopName: row.shopName,
        startTime: this.listQuery.startTime,
        endTime: this.listQuery.endTime,
      };
      this.$router.push({
        path: "/statistics/order_statistics_day",
        query: query,
      });
    },
    getFullDate(targetDate) {
      var D, y, m, d;
      if (targetDate) {
        D = new Date(targetDate);
        y = D.getFullYear();
        m = D.getMonth() + 1;
        d = D.getDate();
      } else {
        y = fullYear;
        m = month;
        d = date;
      }
      m = m > 9 ? m : "0" + m;
      d = d > 9 ? d : "0" + d;
      return y + "-" + m + "-" + d;
    },
    formatDate(date) {
      var d = new Date(date),
        month = "" + (d.getMonth() + 1),
        day = "" + d.getDate(),
        year = d.getFullYear();

      if (month.length < 2) month = "0" + month;
      if (day.length < 2) day = "0" + day;

      return [year, month, day].join("-");
    },
    getIndex(index) {
      return index + 1 + (this.listQuery.page - 1) * this.listQuery.limit;
    },
    getOrderIndex(index) {
      return (
        index + 1 + (this.orderTypeQuery.page - 1) * this.orderTypeQuery.limit
      );
    },
    //获取加拿大温哥华的当前时间
    getVancouverDate() {
      const options = { timeZone: "America/Vancouver" };
      const vancouverDate = new Date().toLocaleDateString("en-CA", options);
      return vancouverDate;
    },
    //获取加拿大温哥华当月第一天的时间
    getFirstDayOfMonth(dateString) {
      // 创建一个新的 Date 对象
      const date = new Date(dateString);
      // 将日期设置为月份的第一天
      date.setDate(1);
      // 获取年月日并返回
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
  },
  watch: {
    "regionOptions.regionIds": function (newVal, oldVal) {
      // if(newVal && newVal.length > 0){
      this.taxForm.regionId =
        this.regionOptions.regionIds[this.regionOptions.regionIds.length - 1];
      // }
    },
    "regionSearchOptions.regionIds": function (newVal, oldVal) {
      if (newVal && newVal.length > 0) {
        this.listQuery.regionId =
          this.regionSearchOptions.regionIds[
            this.regionSearchOptions.regionIds.length - 1
          ];
      } else {
        this.listQuery.regionId = undefined;
      }
    },
  },
  computed: {
    payTypeList: function () {
      // 支付类型 (1:现金支付,2:礼物卡支付,3:Paypal支付,4:余额支付,5:Clover支付,6:积分兑换)
      const arr = [
        {
          value: "1",
          label: this.$t("Cash_Payment"),
        },
        {
          value: "2",
          label: this.$t("Gift_Card_Payment"),
        },
        {
          value: "3",
          label: this.$t("Paypal"),
        },
        {
          value: "4",
          label: this.$t("Pay_by_Balance"),
        },
        {
          value: "5",
          label: this.$t("Pay_by_Clover"),
        },
        {
          value: "6",
          label: this.$t("Points_Exchange"),
        },
      ];
      return arr;
    },
    orderSourceList: function () {
      // 订单来源 1:手机app下单,2:门店下单,3:官网商城,4:订阅
      const arr = [
        {
          value: "1",
          label: this.$t("Phone_App"),
        },
        {
          value: "2",
          label: this.$t("Store_Order"),
        },
        {
          value: "3",
          label: this.$t("Online_Mall"),
        },
        {
          value: "4",
          label: this.$t("Subscription"),
        },
      ];
      return arr;
    },
  },
};
</script>

<style scoped>
.table-layout {
  margin-top: 20px;
}

.table-cell {
  padding: 10px;
  font-size: 14px;
  color: #606266;
  text-align: center;
  overflow: hidden;
}

.table-cell-title {
  padding: 10px;
  background: #f2f6fc;
  text-align: center;
  font-size: 14px;
  color: #303133;
}
</style>
